package com.zhiwang.planet.ui.my.reward


import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView

import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerListComponent
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.ScalarPresenter
import com.zhiwang.planet.mvp.v.KmView
import com.zhiwang.planet.mvp.v.RewardListView
import com.zhiwang.planet.mvvm.model.ListReponseWrapper
import com.zhiwang.planet.mvvm.model.entity.KmInfo
import com.zhiwang.planet.mvvm.model.entity.Reward
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.InputPromotionDialog
import kotlinx.android.synthetic.main.fragment_rewards.*
import kotlinx.android.synthetic.main.item_withdraw_record.view.*
import kotlinx.android.synthetic.main.km_dialog_layout.view.*
import javax.inject.Inject

/**
 * A simple [Fragment] subclass.
 */
class RewardsFragment : BaseFragment, RewardListView, KmView, InputPromotionDialog.Companion.OnPromoteListener {

    @Inject
    lateinit var presenter: ScalarPresenter

    var page = 1


    var rewardMode = false

    /**
     * [rewardMode] true 我的奖品  ;false 我的福利卡
     */
    constructor(rewardMode: Boolean) : super() {
        this.rewardMode = rewardMode;
    }

    private val rewardList = arrayListOf<Reward>()
    private val adapter = RewardAdapter()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerListComponent.builder()
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        presenter.rewardListView = this
        presenter.kmView = this
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragment_rewards, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


    private fun init() {
        recyclerView.adapter = adapter
        smartRefresh.setOnRefreshListener { refresh() }
        smartRefresh.setOnLoadMoreListener { loadMore() }
        if (rewardMode)
            presenter.getRewardList(page)
        else presenter.getBonusCardList(page)
    }

    private fun loadMore() {
        if (rewardMode)
            presenter.getRewardList(page + 1)
        else presenter.getBonusCardList(page + 1)
    }

    private fun refresh() {
        if (rewardMode)
            presenter.getRewardList(1)
        else presenter.getBonusCardList(page)
    }


    /**
     * 刷新 和 加载更多的逻辑都在里面；根据 page 字段区分 刷新 和 加载更多
     */
    override fun onLoadReward(body: ListReponseWrapper<Reward>) {
        page = body.currPage
        if (body.currPage == 1) {//说明是刷新（或者是第一次进入获取数据）
            rewardList.clear()
            adapter.notifyDataSetChanged()

            if (body.dataList.isEmpty()) emptyView.setVisible()
            else emptyView.setGone()
        }

        val oldList = ArrayList(rewardList)
        rewardList.addAll(body.dataList)
        smartRefresh.setEnableLoadMore(body.hasMore == 1)
        DiffUtil
                .calculateDiff(DiffCallBack(oldList, rewardList))
                .dispatchUpdatesTo(adapter)
        smartRefresh.setEnableLoadMore(body.hasMore == 1)
        smartRefresh.finishRefresh()
        smartRefresh.finishLoadMore()
    }


    private fun showKmAlertDialog(name: String, kmNumber: String, kmPassword: String) {
        val view = layoutInflater.inflate(R.layout.km_dialog_layout, null)
        view.km_name.text = name
        view.km_number.text = "卡号：$kmNumber"
        view.km_secret.text = "卡密：$kmPassword"
        view.dialog_button.text = "我知道了"
        val alertDialog = AlertDialog.Builder(requireContext())
                .setView(view)
                .create()
        alertDialog
                .show()
        view.dialog_button.setOnClickListener {
            alertDialog.dismiss()
        }
        view.km_number.setOnClickListener {
            activity?.copy(kmNumber)
            Toaster.message("已复制卡号")
        }

        view.km_secret.setOnClickListener {
            activity?.copy(kmPassword)
            Toaster.message("已复制卡密")
        }
    }

    private fun showCardTransformDialog(name: String, kmNumber: String, kmPassword: String) {
        val view = layoutInflater.inflate(R.layout.km_card_transform_dialog_layout, null)

        view.km_name.text = name
        view.km_number.text = "$kmNumber*$kmPassword"
//        view.km_secret.text = "卡密：$kmPassword"
        view.dialog_button.text = "我知道了"
        val alertDialog = AlertDialog.Builder(requireContext())
                .setView(view)
                .create()
        alertDialog
                .show()
        view.dialog_button.setOnClickListener {
            alertDialog.dismiss()
        }
        view.km_number.setOnClickListener {
            activity?.copy("$kmNumber*$kmPassword")
            Toaster.message("已复制卡号卡密")
        }

        view.km_secret.setOnClickListener {
            activity?.copy(kmPassword)
            Toaster.message("已复制卡密")
        }
    }


    inner class RewardAdapter : RecyclerView.Adapter<RewardAdapter.ItemViewHolder>() {

        private val itemClickListener = View.OnClickListener {
            val position = recyclerView.getChildAdapterPosition(it)
            val data = rewardList[position]
            tryFetchKm(data.id)
        }

        override fun getItemCount() = rewardList.size

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
            return ItemViewHolder(layoutInflater.inflate(R.layout.item_withdraw_record, parent, false))
        }

        override fun onBindViewHolder(viewHolder: ItemViewHolder, p1: Int) {
            viewHolder.bind()
        }

        inner class ItemViewHolder(var view: View) : RecyclerView.ViewHolder(view) {

            init {

            }

            fun bind() {
                val reward = rewardList[adapterPosition]
                view.withdraw_amount.setGone()
                view.withdraw_type.text = reward.name
                view.withdraw_date.text = reward.time

                val color = if (reward.withdrawTime != 0L)
                    R.color.gray
                else R.color.colorOrange
                view.withdraw_state.setTextColor(ContextCompat.getColor(context!!, color))

                view.withdraw_state.text = reward.status_txt
//                view.withdraw_state.text = when (rewardList[adapterPosition].status) {
//                    0 -> "待审核"
//                    10 -> "提取卡密"
//                    20 -> "审核不通过"
//                    40 -> "发放失败"
//                    else -> ""
//                }

                if (reward.status == 30) {
                    view.setOnClickListener(itemClickListener)
                }
            }

        }
    }

    private var kmId = ""
    private var pwd = ""
    private var tmpPwd = ""
    private fun tryFetchKm(id: String) {
        kmId = id
        if (pwd.isNotEmpty()) {
            if (rewardMode)
                presenter.getKmInfo(kmId, pwd)
            else presenter.getCardInfo(kmId, pwd)
        } else InputPromotionDialog.create(requireContext(), this)
    }

    override fun onPromote(pwd: String) {
        tmpPwd = pwd
        if (rewardMode)
            presenter.getKmInfo(kmId, pwd)
        else presenter.getCardInfo(kmId, pwd)
    }

    override fun onLoadKmInfo(kmInfo: KmInfo) {
        pwd = tmpPwd
        if (rewardMode)
            showKmAlertDialog(kmInfo.goods_name, kmInfo.kmNumber, kmInfo.kmPassword)
        else showCardTransformDialog(kmInfo.goods_name, kmInfo.kmNumber, kmInfo.kmPassword)
    }
}
